#! /usr/bin/env fish

function echo_argv
	for each in $argv
		echo argument: $each
	end
end

function main
	if not command -q jq;
		log_fatal 'reuqire "jq", install it first'
	end

	argparse 'i/init' 'u/update' -- $argv

	if set -q _flag_init
		install_plug
		or log_fatal 'failed to install plug'

		out_plug_list > ~/.vim/plug-list.vim

		printf 'Add "source ~/.vim/plug-list.vim" into your vim initialize file.\n'
		return
	end

	if set -q _flag_update
		out_plug_list > ~/.vim/plug-list.vim
	vim +:PlugInstall +:qa

		return
	end

	printf 'plugctl -i,--init	init vim plugins\n'
	printf 'plugctl -u,--update  update plugins based on index.json\n'
end

function install_plug
	set -l remote (jq -r .plug.remote index.json)
	set -l upstream (jq -r .plug.upstream index.json)
	set -l plug_dir ~/.vim/plug.git

	if test ! -d $plug_dir/.git
		git clone $remote $plug_dir
		or log_fatal 'clone %s failed' $remote
	end

	# create soft link to autoload/plug.vim
	mkdir -p ~/.vim/autoload
	ln -sf $plug_dir/plug.vim ~/.vim/autoload/plug.vim
end

function log_fatal
	echo -n 'FATAL: ' >&2
	printf $argv >&2
	echo >&2
	exit 1
end

function log_printf
	printf $argv >&2
	echo >&2
end

function out_plug_list
	set -l n (jq '.install | length' index.json)

	echo 'call plug#begin(\'~/.vim/plug-install\')'
	for i in (seq 0 (math $n - 1))
		set -l remote (jq -r ".install[$i].remote" index.json)
		set -l name   (jq -r ".install[$i].name" index.json)

		printf '\tPlug \'%s\'\n' $remote
		log_printf 'Plugin: %s, %s' $name $remote
	end

	echo 'call plug#end()'
end

main $argv
